<template>
	<view class="page-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="nav-left" @tap="goBackToHome">
				<image class="back-icon" src="/static/home.svg"></image>
				<text class="back-text">首页</text>
			</view>
			<text class="nav-title">帖子详情</text>
			<view class="nav-right"></view>
		</view>
		
		<scroll-view class="scrollarea" scroll-y type="list">
			<view class="container">
			<!-- 帖子详情 -->
			<view class="post-detail" v-if="post">
				<view class="post-header">
					<view class="post-avatar">
						<image :src="post.avatar" class="avatar-image"></image>
					</view>
					<view class="post-info">
						<text class="post-author">{{ post.author }}</text>
						<text class="post-time">{{ post.time }}</text>
					</view>
					<view class="post-category" :class="post.categoryClass">
						{{ getCategoryName(post.categoryId) }}
					</view>
				</view>
				
				<view class="post-content">
					<text class="post-title">{{ post.title }}</text>
					<text class="post-text">{{ post.content }}</text>
				</view>
				
				<view class="post-stats">
					<view class="stat-item">
						<image src="/static/collection.svg" class="stat-icon"></image>
						<text class="stat-text">{{ post.likes }}</text>
					</view>
					<view class="stat-item">
						<image src="/static/message.svg" class="stat-icon"></image>
						<text class="stat-text">{{ comments.length }}</text>
					</view>
					<view class="stat-item">
						<image src="/static/footprint.svg" class="stat-icon"></image>
						<text class="stat-text">{{ post.views }}</text>
					</view>
				</view>
			</view>
			
			<!-- 评论区域 -->
			<view class="comments-section">
				<view class="section-header">
					<text class="section-title">评论 ({{ comments.length }})</text>
				</view>
				
				<view class="comment-list" v-if="comments.length > 0">
					<view 
						class="comment-item" 
						v-for="comment in comments" 
						:key="comment.id"
					>
						<view class="comment-avatar">
							<image :src="comment.avatar" class="avatar-image"></image>
						</view>
						<view class="comment-content">
							<view class="comment-header">
								<text class="comment-author">{{ comment.author }}</text>
								<text class="comment-time">{{ comment.time }}</text>
							</view>
							<text class="comment-text">{{ comment.content }}</text>
						</view>
					</view>
				</view>
				
				<view class="empty-comments" v-else>
					<image src="/static/empty-message.svg" class="empty-icon"></image>
					<text class="empty-text">暂无评论，快来抢沙发吧！</text>
				</view>
			</view>
			
			<!-- 评论输入区域 -->
			<view class="comment-input-section">
				<view class="comment-input-box">
					<input 
						class="comment-input" 
						placeholder="写下你的评论..." 
						v-model="newComment"
						@confirm="submitComment"
						maxlength="500"
						:disabled="submitting"
					/>
					<view class="comment-btn" :class="{ 'disabled': !newComment.trim() || submitting }" @tap="submitComment">
						<text class="comment-btn-text">{{ submitting ? '发送中...' : '发送' }}</text>
					</view>
				</view>
				<view class="comment-tip" v-if="newComment.length > 0">
					<text class="tip-text">{{ newComment.length }}/500</text>
				</view>
			</view>
		</view>
		</scroll-view>
	</view>
</template>

<script>
		import { getComments, addComment, getPostById } from '@/api/forum.js'
	
	export default {
		data() {
			return {
				postId: null,
				post: null,
				comments: [],
				newComment: '',
				loading: false,
				submitting: false // 添加提交状态
			}
		},
		onLoad: function(options) {
			console.log('帖子详情页加载', options);
			this.postId = options.id;
			if (this.postId) {
				this.loadPostDetail();
				this.loadComments();
			}
		},
		methods: {
			// 返回首页
			goBackToHome: function() {
				// 使用reLaunch确保跳转到首页并清空页面栈
				uni.reLaunch({
					url: '/pages/index/index',
					success: function() {
						console.log('成功跳转到首页');
					},
					fail: function(err) {
						console.error('跳转首页失败:', err);
						// 如果reLaunch失败，尝试使用navigateTo
						uni.navigateTo({
							url: '/pages/index/index'
						});
					}
				});
			},
			
			// 加载帖子详情
			loadPostDetail: function() {
				if (!this.postId) {
					console.error('帖子ID不能为空');
					return;
				}
				
				// 显示加载状态
				this.loading = true;
				
				// 从后端获取帖子详情
				getPostById(this.postId).then(res => {
					console.log('帖子详情数据:', res);
					
					if (res.data) {
						// 处理帖子数据，确保字段完整
						this.post = {
							id: res.data.id,
							title: res.data.title || '无标题',
							content: res.data.content || '暂无内容',
							author: res.data.author || '匿名用户',
							time: this.formatTime(res.data.createTime) || '未知时间',
							categoryId: res.data.categoryId || 1,
							categoryClass: this.getCategoryClass(res.data.categoryId),
							avatar: this.getUserAvatar(res.data.userId),
							likes: res.data.likes || 0,
							comments: res.data.comments || 0,
							views: res.data.views || 0
						};
						
						console.log('处理后的帖子数据:', this.post);
					} else {
						// 如果后端返回空数据，使用默认数据
						this.post = {
							id: this.postId,
							title: '帖子不存在',
							content: '该帖子可能已被删除或不存在',
							author: '系统',
							time: '未知时间',
							categoryId: 1,
							categoryClass: 'default-category',
							avatar: '/static/system-avatar.svg',
							likes: 0,
							comments: 0,
							views: 0
						};
					}
					
					this.loading = false;
				}).catch(err => {
					console.error('获取帖子详情失败:', err);
					this.loading = false;
					
					// 显示错误信息
					uni.showToast({
						title: '获取帖子详情失败',
						icon: 'none',
						duration: 2000
					});
					
					// 使用默认数据
					this.post = {
						id: this.postId,
						title: '加载失败',
						content: '无法获取帖子内容，请检查网络连接',
						author: '系统',
						time: '未知时间',
						categoryId: 1,
						categoryClass: 'default-category',
						avatar: '/static/system-avatar.svg',
						likes: 0,
						comments: 0,
						views: 0
					};
				});
			},
			// 加载评论
			loadComments: function() {
				this.loading = true;
				getComments().then(res => {
					console.log('评论数据:', res);
					if (res.data && Array.isArray(res.data)) {
						// 过滤出当前帖子的评论
						const postComments = res.data.filter(comment => comment.postId == this.postId);
						// 处理评论数据
						const processedComments = postComments.map(comment => ({
							...comment,
							author: `用户${comment.userId}`,
							time: this.formatTime(comment.createTime),
							avatar: '/static/study-avatar.svg'
						}));
						this.comments = processedComments;
					} else {
						this.comments = [];
					}
					this.loading = false;
				}).catch(err => {
					console.error('加载评论失败:', err);
					this.comments = [];
					this.loading = false;
				});
			},
			// 提交评论
			submitComment: function() {
				if (!this.newComment.trim()) {
					uni.showToast({
						title: '请输入评论内容',
						icon: 'none'
					});
					return;
				}
				
				if (this.submitting) {
					return; // 防止重复提交
				}
				
				this.submitting = true;
				
				const commentData = {
					postId: parseInt(this.postId),
					userId: 1, // 这里应该获取当前用户ID
					content: this.newComment.trim(),
					createTime: new Date().toISOString() // 添加创建时间
				};
				
				console.log('提交评论数据:', commentData);
				
				addComment(commentData).then(res => {
					console.log('评论提交结果:', res);
					this.submitting = false;
					
					// 确保响应数据是字符串
					const responseData = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
					
					if (responseData === '添加成功') {
						uni.showToast({
							title: '评论成功',
							icon: 'success'
						});
						this.newComment = '';
						// 重新加载评论
						this.loadComments();
					} else {
						uni.showToast({
							title: responseData || '评论失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('评论提交失败:', err);
					this.submitting = false;
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				});
			},
			// 格式化时间
			formatTime: function(time) {
				if (!time) return '';
				const now = new Date();
				const postTime = new Date(time);
				const diff = now - postTime;
				const minutes = Math.floor(diff / 60000);
				const hours = Math.floor(diff / 3600000);
				const days = Math.floor(diff / 86400000);
				
				if (minutes < 60) {
					return `${minutes}分钟前`;
				} else if (hours < 24) {
					return `${hours}小时前`;
				} else {
					return `${days}天前`;
				}
			},
			// 获取分类名称
			getCategoryName: function(categoryId) {
				const categoryMap = {
					1: '数学',
					2: '语文',
					3: '英语',
					4: '物理',
					5: '化学',
					6: '生物',
					7: '历史',
					8: '地理',
					9: '政治'
				};
				return categoryMap[categoryId] || '未知分类';
			},
			
			// 获取分类样式类名
			getCategoryClass: function(categoryId) {
				const classMap = {
					1: 'math-category',
					2: 'chinese-category',
					3: 'english-category',
					4: 'physics-category',
					5: 'chemistry-category',
					6: 'biology-category',
					7: 'history-category',
					8: 'geography-category',
					9: 'politics-category'
				};
				return classMap[categoryId] || 'default-category';
			},
			
			// 获取用户头像
			getUserAvatar: function(userId) {
				// 根据用户ID返回不同的头像
				const avatarMap = {
					1: '/static/teacher-avatar.svg',
					2: '/static/study-avatar.svg',
					3: '/static/system-avatar.svg'
				};
				return avatarMap[userId] || '/static/study-avatar.svg';
			},
			
			// 格式化时间
			formatTime: function(timeString) {
				if (!timeString) return '未知时间';
				
				try {
					const time = new Date(timeString);
					const now = new Date();
					const diff = now - time;
					
					// 计算时间差
					const minutes = Math.floor(diff / (1000 * 60));
					const hours = Math.floor(diff / (1000 * 60 * 60));
					const days = Math.floor(diff / (1000 * 60 * 60 * 24));
					
					if (minutes < 1) {
						return '刚刚';
					} else if (minutes < 60) {
						return `${minutes}分钟前`;
					} else if (hours < 24) {
						return `${hours}小时前`;
					} else if (days < 7) {
						return `${days}天前`;
					} else {
						// 超过一周显示具体日期
						return time.toLocaleDateString('zh-CN', {
							year: 'numeric',
							month: '2-digit',
							day: '2-digit'
						});
					}
				} catch (e) {
					console.error('时间格式化失败:', e);
					return '未知时间';
				}
			}
		}
	}
</script>

<style>
	page {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: #f8fafc;
	}
	
	/* 页面容器 */
	.page-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
	}
	
	/* 自定义导航栏 */
	.custom-navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20px 16px 12px 16px;
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-bottom: 1px solid rgba(0, 0, 0, 0.1);
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
		position: sticky;
		top: 0;
		z-index: 1000;
		margin-top: 20px;
	}
	
	.nav-left {
		display: flex;
		align-items: center;
		padding: 8px 12px;
		border-radius: 20px;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
		transition: all 0.3s ease;
	}
	
	.nav-left:active {
		transform: scale(0.95);
		box-shadow: 0 1px 4px rgba(102, 126, 234, 0.4);
	}
	
	.back-icon {
		width: 18px;
		height: 18px;
		margin-right: 6px;
		filter: brightness(0) invert(1);
	}
	
	.back-text {
		color: white;
		font-size: 14px;
		font-weight: 600;
	}
	
	.nav-title {
		font-size: 18px;
		font-weight: 700;
		color: #1e293b;
		text-align: center;
		flex: 1;
	}
	
	.nav-right {
		width: 60px;
		height: 40px;
	}

	.scrollarea {
		flex: 1;
	}

	.container {
		padding: 20px 8px; /* 与首页论坛区域保持一致的左右边距 */
		padding-bottom: 120px;
		min-height: 100vh;
		max-width: calc(100% - 16px); /* 与首页论坛区域保持一致的宽度 */
		margin: 0 auto; /* 居中显示 */
	}

	/* 帖子详情样式 */
	.post-detail {
		background: white;
		border-radius: 20px;
		padding: 24px;
		margin: 40px 0 20px 0; /* 增加顶部间距，下移帖子内容 */
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
		border: 1px solid rgba(0, 0, 0, 0.05);
	}

	.post-header {
		display: flex;
		align-items: center;
		gap: 12px;
		margin-bottom: 20px;
	}

	.post-avatar {
		width: 48px;
		height: 48px;
		border-radius: 50%;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	.avatar-image {
		width: 100%;
		height: 100%;
	}

	.post-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 6px;
	}

	.post-author {
		font-size: 16px;
		font-weight: 700;
		color: #1f2937;
	}

	.post-time {
		font-size: 14px;
		color: #6b7280;
	}

	.post-category {
		padding: 8px 16px;
		border-radius: 16px;
		font-size: 14px;
		font-weight: 600;
		color: white;
	}

	.math-category {
		background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
	}

	.chinese-category {
		background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
	}

	.english-category {
		background: linear-gradient(135deg, #10b981 0%, #059669 100%);
	}

	.physics-category {
		background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
	}

	.chemistry-category {
		background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
	}

	.post-content {
		margin-bottom: 20px;
	}

	.post-title {
		font-size: 22px; /* 增大标题字体 */
		font-weight: 800;
		color: #1f2937;
		line-height: 1.4;
		margin-bottom: 20px; /* 增加底部间距 */
		display: block;
		text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); /* 添加文字阴影 */
	}

	.post-text {
		font-size: 17px; /* 增大内容字体 */
		color: #374151;
		line-height: 1.7; /* 增加行高，提升可读性 */
		display: block;
		word-wrap: break-word; /* 允许长单词换行 */
		word-break: break-word; /* 强制换行 */
		white-space: normal; /* 允许正常换行 */
	}

	.post-stats {
		display: flex;
		gap: 24px;
		align-items: center;
		padding-top: 16px;
		border-top: 1px solid #e5e7eb;
	}

	.stat-item {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.stat-icon {
		width: 18px;
		height: 18px;
		opacity: 0.6;
	}

	.stat-text {
		font-size: 14px;
		color: #6b7280;
		font-weight: 600;
	}

	/* 评论区域样式 */
	.comments-section {
		background: white;
		border-radius: 20px;
		padding: 24px;
		margin-bottom: 20px;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
		border: 1px solid rgba(0, 0, 0, 0.05);
		width: 100%; /* 确保与帖子宽度一致 */
	}

	.section-header {
		margin-bottom: 20px;
		padding-bottom: 12px;
		border-bottom: 1px solid #e5e7eb;
	}

	.section-title {
		font-size: 20px; /* 增大评论标题字体 */
		font-weight: 700;
		color: #1f2937;
		text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); /* 添加文字阴影 */
	}

	.comment-list {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.comment-item {
		display: flex;
		gap: 12px;
		padding: 18px; /* 增加内边距 */
		background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); /* 添加渐变背景 */
		border-radius: 18px; /* 增加圆角 */
		border: 1px solid #e5e7eb;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); /* 添加阴影 */
		transition: all 0.3s ease; /* 添加过渡效果 */
	}
	
	.comment-item:hover {
		transform: translateY(-2px); /* 悬停效果 */
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.comment-avatar {
		width: 36px;
		height: 36px;
		border-radius: 50%;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		flex-shrink: 0;
	}

	.comment-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.comment-header {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.comment-author {
		font-size: 14px;
		font-weight: 600;
		color: #1f2937;
	}

	.comment-time {
		font-size: 12px;
		color: #6b7280;
	}

	.comment-text {
		font-size: 15px; /* 增大评论文字 */
		color: #374151;
		line-height: 1.6; /* 增加行高 */
		word-wrap: break-word; /* 允许长单词换行 */
		word-break: break-word; /* 强制换行 */
		white-space: normal; /* 允许正常换行 */
	}

	.empty-comments {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 16px;
		padding: 40px 20px;
	}

	.empty-icon {
		width: 80px;
		height: 80px;
		opacity: 0.5;
	}

	.empty-text {
		font-size: 16px;
		color: #6b7280;
		font-weight: 500;
	}

	/* 评论输入区域样式 */
	.comment-input-section {
		position: fixed;
		bottom: 0;
		left: 8px; /* 与帖子保持一致的左边距 */
		right: 8px; /* 与帖子保持一致的右边距 */
		background: white;
		padding: 16px 20px;
		border-top: 1px solid #e5e7eb;
		box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.08);
		border-radius: 20px 20px 0 0; /* 添加顶部圆角 */
	}

	.comment-input-box {
		display: flex;
		align-items: center;
		gap: 12px;
		background: #f8fafc;
		border-radius: 25px;
		padding: 8px 16px;
		border: 1px solid #e5e7eb;
	}

	.comment-input {
		flex: 1;
		font-size: 16px;
		color: #1f2937;
		background: transparent;
		border: none;
		outline: none;
		padding: 8px 0;
	}

	.comment-input::placeholder {
		color: #9ca3af;
	}

	.comment-btn {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 20px;
		padding: 8px 16px;
		transition: all 0.3s ease;
	}

	.comment-btn:active {
		transform: scale(0.95);
		opacity: 0.8;
	}

	.comment-btn-text {
		font-size: 14px;
		font-weight: 600;
		color: white;
	}
	
	.comment-btn.disabled {
		opacity: 0.5;
		background: #9ca3af;
	}
	
	.comment-tip {
		text-align: right;
		padding: 8px 16px 0 0;
	}
	
	.tip-text {
		font-size: 12px;
		color: #9ca3af;
	}
</style>
